package com.qhhc.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 语音与说话人识别服务的配置类
 */
@Configuration
@EnableAsync
@EnableScheduling
public class VoiceServiceConfig {

    @Value("${voice.service.url:http://localhost:8000}")
    private String voiceServiceUrl;

    @Value("${voice.service.thread.core-pool-size:5}")
    private int corePoolSize;

    @Value("${voice.service.thread.max-pool-size:10}")
    private int maxPoolSize;

    @Value("${voice.service.thread.queue-capacity:100}")
    private int queueCapacity;

    @Value("${voice.service.thread.keep-alive-seconds:60}")
    private int keepAliveSeconds;

    /**
     * 语音服务异步任务线程池
     */
    @Bean(name = "voiceTaskExecutor")
    public Executor voiceTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setKeepAliveSeconds(keepAliveSeconds);
        executor.setThreadNamePrefix("voice-service-");

        // 当线程池已满时，使用调用者线程执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());

        // 初始化线程池
        executor.initialize();
        return executor;
    }

    /**
     * 说话人特征库清理任务的线程池
     */
    @Bean(name = "speakerTaskExecutor")
    public Executor speakerTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(2);
        executor.setMaxPoolSize(4);
        executor.setQueueCapacity(10);
        executor.setThreadNamePrefix("speaker-service-");

        // 初始化线程池
        executor.initialize();
        return executor;
    }
}